// 此组件是：收藏的课程中的课程列表 组件
// this.props.dataList 是接受的父组件 传过来的 数据，进行遍历

import React from 'react';
import {
    Text,
    View,
    StyleSheet,
    Image,
    FlatList,
    TouchableOpacity,
    TouchableWithoutFeedback,
    AsyncStorage,
    Platform
} from 'react-native';
var Dimensions = require('Dimensions');
var { width } = Dimensions.get('window');
import { Toast } from 'teaset';
import {updateOrder}  from '../api/my';
import {setSpText,setHW} from './ScreenUtil'
// import { format } from 'path';
export default class MyCourseList extends React.Component {
    // 初始化模拟数据
    constructor(props) {
        super(props);
        this.state = {
            isReach:false,
            refreshing: false,//初始化不刷新
        }
    }
    render() {
        return (
            <View style={styles.itemBox}>
                <FlatList
                    data={this.props.dataList}
                    extraData={this.state}
                    showsVerticalScrollIndicator={false}
                    renderItem={({ item }) => this.renderItem(item)}
                    keyExtractor={(item, index) => index}
                />
            </View>
        );
    }
    // 每一行课程
    renderItem(item) {
        return (
            <TouchableWithoutFeedback onPress={() => this.goDetailPage(item)}>
                <View style={styles.item}>
                    <View style={styles.top}>
                        <View style={styles.itemLeft}>
                            <Image style={styles.teacherIcon} source={{ uri: item.PIC }} />
                        </View>
                        <View style={styles.itemRight}>
                            <View style={styles.title}>
                                <View style={styles.titleLeft}>
                                    {this.showTag(item)}
                                    <Text style={styles.titleText}>{this.MoreText(item.TITLE,6)}</Text>
                                </View>
                                {this.showBuyStatus(item)}
                            </View>
                            <Text style={styles.teacherName}>授课老师：{this.MoreText(item.TEACHERNAME,4)}</Text>
                            <View style={styles.tagListBox}>
                                <View style={styles.tagList}>
                                    <View style={styles.tagsRadius}>
                                        <Text style={styles.tags}>{item.GRADE}</Text>
                                    </View>
                                    <View style={styles.tagsRadius}>
                                        <Text style={styles.tags}>{item.SUBJECTNAME}</Text>
                                    </View>
                                </View>
                                <View style={styles.moneyPrice}>
                                    <Text style={styles.priceText}>价格：</Text>
                                    <Text style={styles.price}>¥</Text>
                                    <Text style={styles.money}>{item.MONEY}</Text>
                                </View>
                            </View>
                        </View>
                    </View>
                    {this.showBtn(item)}
                    {this.whereForm(item)}
                </View>
            </TouchableWithoutFeedback>
        )
    }
    // 是课时跳课时 课程跳课程
    goDetailPage(item) {
        let that=this;
        if (item.COURSE_TYPE == '0') {//课程
            this.props.navigation.navigate('DetailLesson', {
                courseId: item.COURSE_ID,
                refreshPage: function () {
                    //去让父亲组件刷新
                    that.props.ResetSearch&&that.props.ResetSearch()
                }
            });
        } else {//课时
            this.props.navigation.navigate('KeShiIndex', {
                id: item.COURSE_ID,
                refreshPage: function () {
                    //去让父亲组件刷新
                    that.props.ResetSearch&&that.props.ResetSearch()
                }
            });
        }
    }
    // 展示支付状态  状态0已退回1待支付,2支付成功
    showBuyStatus(item) {
        if (item.STATUS == '4') {
            return (
                <Text style={styles.buyStatus}>交易关闭</Text>
            )
        }
        if (item.STATUS == '1') {
            return (
                <Text style={styles.buyStatus}>待支付</Text>
            )
        }
        if (item.STATUS == '2') {
            return (
                <Text style={styles.buyStatus}>已支付</Text>
            )
        }
    }
    // 待支付 才显示 取消订单和 立即付款
    showBtn(item) {
        if (item.STATUS == '1') {
            return (
                <View style={styles.bottom}>
                    <TouchableOpacity
                        style={styles.btn}
                        onPress={() => this.cancelOrder(item)} >
                        <Text style={styles.btnText}>取消订单</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={[styles.btn, styles.btnGoBuy]}
                        onPress={() => this.goToPay(item)} >
                        <Text style={styles.btnGoBuyText}>立即付款</Text>
                    </TouchableOpacity>
                </View>
            )
        }
    }
   
    // 取消订单
    cancelOrder(item) {
        this.props.loading && this.props.loading(true)
        let json = {
            ID: item.ID
        }
        if(this.props.currentTabName=='AllOrder'){//所有订单// 不刷新，只更新状态
            this.setState({
                isReach:!this.state.isReach
            });
            item.STATUS='4'
            Toast.message("取消成功")
        }
        updateOrder(json).then(() => {
            if(this.props.currentTabName=='NoBuy'){
                updateOrder(json).then(() => {
                    let tabName='NoBuy';
                    this.props.loading && this.props.loading(false)
                    this.props.seachData && this.props.seachData(tabName)
                    Toast.message("取消成功")
                }).catch(() => {
                    this.props.loading && this.props.loading(false)
                })
            }
        }).catch(() => {
            this.props.loading && this.props.loading(false)
        })
    }
    // 立即付款
    goToPay(item) {
        let payCourseInfo = {
            BASICINFO: {},
            LISTCOURSE: [],
            toPage: 'DetailLesson',//默认跳到课程
        }
        payCourseInfo.toPage=item.COURSE_TYPE=='1'?'KeShiIndex':'DetailLesson';
        payCourseInfo.BASICINFO.COURSE_NAME = item.TITLE;//课程名字
        payCourseInfo.BASICINFO.STOP_TIME = item.STOP_TIME;//截至时间
        payCourseInfo.BASICINFO.TEACHER_NAME = item.TEACHERNAME;//老师名字
        payCourseInfo.BASICINFO.COURSE_ID = item.COURSE_ID//课程id
        payCourseInfo.BASICINFO.TOTLE_MONEY = item.MONEY;//价格
        let obj = {
            "COURSE_TYPE": item.COURSE_TYPE,//0 是课程 1是课时
            "COURSE_ID": item.COURSE_ID,//课程id 或者课程id 用的一个字段
            "MONEY": item.MONEY,
            "COURSE_NAME": item.TITLE
        }
        payCourseInfo.LISTCOURSE.push(obj)
        AsyncStorage.setItem('payCourseInfo', JSON.stringify(payCourseInfo));
        this.props.navigation.navigate("PayScreen");
    }
    async btnParent() {
        AsyncStorage.getItem('payCourseInfo').then((res) => {
            global.log(res, '-=========')
        })
    }
    // 展示系列课
    showTag(item) {
        if (item.COURSE_TYPE == '0') {
            return (
                <View style={styles.tagRadius}>
                    <Text style={styles.tagName}>系列课</Text>
                </View>
            )
        }
    }
    // 本课来源
    whereForm(item) {
        if (item.COURSE_TYPE !== '0') {
            if(item.STATE!=='2'&&item.COURSESTATUS!=='2'){// 该课程没有被下架
                return (
                     <View>
                        <View style={styles.line}></View>
                        <View style={styles.enterCourseBox}>
                            <View style={styles.enterCourse}>
                                <Text style={styles.text}>本课时来源于：{this.MoreText(item.UPTITLE,10)}</Text>
                                <View style={styles.enterRight}>
                                    <Text style={styles.enterText} onPress={() => this.enterCourse(item.FCOURSEID)}>进入该系列课</Text>
                                    <Image style={styles.enterCourseIcon} source={require('../assets/imgs/enter.png')} />
                                </View>
                            </View>
                        </View>
                    </View>
                )
            }else{
                return null
            }
        }
    }
    // 最多字符
    MoreText(text, MaxNum) {
        if (text) {
            if (text.length > MaxNum) {
                return (
                    text.substring(0, MaxNum) + '...'
                )
            } else {
                return (
                    text
                )
            }
        }
    }
    // 进入该系列课 跳到课程
    enterCourse(courseId) {
        this.props.navigation.navigate('DetailLesson', {
            courseId: courseId
        });
    }
}

const styles = StyleSheet.create({
    itemBox: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        alignItems: 'flex-start',
        backgroundColor: '#F7F7F9',
    },
    item: {
        paddingTop: setHW(30),
        paddingLeft: setHW(16),
        paddingRight: setHW(16),
        backgroundColor: '#fff',
        marginBottom: setHW(10),
    },
    line:{
        height:0.5,
        width:width - setHW(40),
        backgroundColor:'#EBEBEB',
    },
    enterCourseBox: {
        backgroundColor: '#fff',
    },
    enterCourse: {
        backgroundColor: '#fff',
        height: setHW(80),
        alignItems:'center',
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    enterRight: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
    },
    text: {
        color: "#999",
        fontSize:setSpText(24),
    },
    enterText: {
        color: '#666',
        textAlign: 'right',
        paddingRight: setHW(8),
        fontSize:setSpText(24),
    },
    enterCourseIcon: {
        width: setHW(20),
        height: setHW(20),
        marginTop: 1,
    },
    moneyPrice: {
        flexDirection: 'row',
    },
    priceText: {
        color: '#666',
        fontSize:setSpText(22),
    },
    price: {
        color: '#666',
        fontSize:setSpText(22),
    },
    money: {
        color: '#666',
        fontSize:setSpText(22),
    },
    top: {
        flexDirection: 'row',
        backgroundColor: '#fff',
        justifyContent: 'flex-start',
        paddingBottom:setHW(20)
    },
    itemLeft: {
        width: setHW(240),
        marginRight: setHW(20),
    },
    teacherIcon: {
        width: setHW(240),
        height: setHW(146),
        resizeMode: 'cover'
    },
    itemRight: {
        width: width - setHW(300),
    },
    title: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: setHW(20),
    },
    titleLeft: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
        height:setHW(36),
        alignItems:'center',
    },
    tagRadius: {
        backgroundColor: '#FF8A00',
        borderRadius: setHW(8),
        marginRight:  setHW(8),
        paddingLeft:  setHW(10),
        paddingRight: setHW(10),
        height:setHW(32),
        justifyContent:'center',
        alignItems:'center',
    },
    tagName: {
        fontSize:setSpText(22),
        color: '#fff',
    },
    titleText: {
        color: '#333',
        fontSize:setSpText(30),
        fontWeight: 'bold',
    },
    buyStatus: {
        fontSize:setSpText(24),
        color: '#FF8A00',
        paddingTop: setHW(4),
        paddingBottom: setHW(4),
    },
    teacherName: {
        fontSize:setSpText(24),
        color: '#333',
        marginBottom: setHW(18),
    },
    tagListBox: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingBottom: setHW(20),
    },
    tagList: {
        flexDirection: 'row',
        justifyContent: 'flex-start'
    },
    tagsRadius:{
        backgroundColor: '#F7F7F9',
        borderRadius: setHW(4),
        paddingLeft: setHW(8),
        paddingRight: setHW(8),
        marginRight: setHW(8),
        height:setHW(36),
        justifyContent:'center',
        alignItems:'center',
    },
    tags: {
        color: '#999999',
        fontSize:setSpText(24),
    },
    bottom: {
        backgroundColor: '#fff',
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems:'center',
        height: setHW(80),
        borderTopWidth: 1,
        borderTopColor: '#EBEBEB',
    },
    btn: {
        borderRadius:setHW(22),
        borderColor: '#999999',
        borderWidth: 1,
        marginLeft: setHW(16),
        width:setHW(120),
        height: setHW(44),
        justifyContent: 'center',
        alignItems: 'center',
    },
    btnGoBuy: {
        borderColor: '#FF8A00',
    },
    btnText: {
        color: '#666',
        fontSize:setSpText(24),
    },
    btnGoBuyText: {
        color: '#FF8A00',
        fontSize:setSpText(24),
    }
});
